package com.kingstar.ceres.data.load;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ElUtil implements BeanFactoryAware {

    private static BeanExpressionResolver resolver;

    private static BeanExpressionContext expressionContext;

    private static BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory factory) throws BeansException {
        beanFactory=factory;
        if (beanFactory instanceof ConfigurableListableBeanFactory){
            resolver=((ConfigurableListableBeanFactory) beanFactory).getBeanExpressionResolver();
            expressionContext=new BeanExpressionContext((ConfigurableListableBeanFactory) beanFactory, null);
        }
    }

    public static Object resolverExpression(String value){
        String resolverValue = resolver(value);
        Object evaluate = resolver.evaluate(resolverValue, expressionContext);
        return evaluate;
    }

    private static String resolver(String value) {
        return beanFactory!=null && beanFactory instanceof ConfigurableBeanFactory ?
                ((ConfigurableBeanFactory)beanFactory).resolveEmbeddedValue(value):value;
    }
}